//! # 组件生命周期管理
//! 
//! 本模块提供了组件生命周期管理的默认实现和相关工具。

use crate::di::traits::*;
use crate::di::models::*;
use rustcloud_core::{ServiceResult, ServiceError};
use std::sync::Arc;
use async_trait::async_trait;

/// 默认的组件生命周期管理器实现
#[derive(Debug)]
pub struct DefaultComponentLifecycleManager {
    state: Arc<tokio::sync::RwLock<ComponentState>>,
    name: String,
}

impl DefaultComponentLifecycleManager {
    pub fn new(name: String) -> Self {
        Self {
            state: Arc::new(tokio::sync::RwLock::new(ComponentState::Uninitialized)),
            name,
        }
    }
}

#[async_trait]
impl ComponentLifecycleManager for DefaultComponentLifecycleManager {
    async fn initialize(&self) -> ServiceResult<()> {
        let mut state = self.state.write().await;
        *state = ComponentState::Initializing;
        tracing::info!("组件 {} 初始化", self.name);
        *state = ComponentState::Initialized;
        Ok(())
    }
    
    async fn start(&self) -> ServiceResult<()> {
        let mut state = self.state.write().await;
        *state = ComponentState::Starting;
        tracing::info!("组件 {} 启动", self.name);
        *state = ComponentState::Running;
        Ok(())
    }
    
    async fn stop(&self) -> ServiceResult<()> {
        let mut state = self.state.write().await;
        *state = ComponentState::Stopping;
        tracing::info!("组件 {} 停止", self.name);
        *state = ComponentState::Stopped;
        Ok(())
    }
    
    async fn destroy(&self) -> ServiceResult<()> {
        let mut state = self.state.write().await;
        *state = ComponentState::Uninitialized;
        tracing::info!("组件 {} 销毁", self.name);
        Ok(())
    }
    
    async fn get_state(&self) -> ComponentState {
        self.state.read().await.clone()
    }
    
    async fn health_check(&self) -> ServiceResult<bool> {
        let state = self.state.read().await;
        Ok(*state == ComponentState::Running)
    }
}